//
//  TL_CommentsViewController.m
//  WXReader
//
//  Created by Andrew on 2018/6/26.
//  Copyright © 2018年 Andrew. All rights reserved.
//

#import "TL_CommentsViewController.h"
#import "TL_CommentsTableViewCell.h"

#import "CXTextView.h"

#import "TL_CommentReplyListViewController.h"

@interface TL_CommentsViewController () <UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate, UITextViewDelegate>
{
    CGFloat keyboardHeight;     //键盘高度
    CGFloat commentViewHeight;
}

@property (nonatomic, strong) CXTextView *commentTextView;

@property (nonatomic, strong) UIView *commentBottomView;

@property (nonatomic, strong) TL_CommentsModel *commentModel;

@property (nonatomic, assign) BOOL isTABAnimated;

@end

@implementation TL_CommentsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initialize];
    [self createSubviews];
//    [self netRequest];
    
    self.currentPageNumber = 1;
    [self.dataSourceArray removeAllObjects];
    [self.mainTableView reloadData];
    [self netRequest];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setStatusBarDefaultStyle];
    
}

- (void)initialize
{
    self.isTABAnimated = NO;
    
    if (self.chapter_id > 0) {
        if (self.productionType == TL_ProductionTypeComic) {
            [self setNavigationBarTitle:WXLocalizedString(@"评论")];
        } else {
            [self setNavigationBarTitle:[NSString stringWithFormat:WXLocalizedString(@"本章评论（%@）"),[TL_UtilsHelper formatStringWithInteger:0]]];
        }
    } else {
        [self setNavigationBarTitle:[NSString stringWithFormat:WXLocalizedString(@"书评（%@）"),[TL_UtilsHelper formatStringWithInteger:0]]];
    }
    [self setNavigationBarTitle:@"All comments"];
    
    commentViewHeight = 30;
    
    NSArray *viewcontrollers = self.navigationController.viewControllers;
    if (viewcontrollers.count <= 1) {
        UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        closeButton.frame = CGRectMake(kHalfMargin, PUB_NAVBAR_OFFSET + 20, 44, 44);
        closeButton.imageEdgeInsets = UIEdgeInsetsMake(12, 12, 12, 12);
        [closeButton setImage:[UIImage imageNamed:@"public_close"] forState:UIControlStateNormal];
        closeButton.tintColor = kBlackColor;
        [closeButton addTarget:self action:@selector(popViewController) forControlEvents:UIControlEventTouchUpInside];
        [self setNavigationBarLeftButton:closeButton];
    }
    
    if (self.pushFromReader) {
        id target = self.navigationController.interactivePopGestureRecognizer.delegate;
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:target action:NSSelectorFromString(@"handleNavigationTransition:")];
        panGesture.delegate = self; // 设置手势代理，拦截手势触发
        [self.view addGestureRecognizer:panGesture];
        
        // 一定要禁止系统自带的滑动手势
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
        
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)name:UIKeyboardWillShowNotification object:nil];
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:)name:UIKeyboardWillHideNotification object:nil];
}


- (void)createSubviews
{
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    [self.view addSubview:self.mainTableView];
    
    [self.mainTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(PUB_NAVBAR_HEIGHT);
        make.width.mas_equalTo(self.view.mas_width);
        make.height.mas_equalTo(self.view.mas_height).with.offset(- PUB_NAVBAR_HEIGHT - PUB_TABBAR_HEIGHT);
    }];
    
    self.commentBottomView = [[UIView alloc] init];
    self.commentBottomView.backgroundColor = kGrayViewColor;
    self.commentBottomView.hidden = YES;
    [self.view addSubview:self.commentBottomView];
    
    [self.commentBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.bottom.mas_equalTo(self.view.mas_bottom);
        make.width.mas_equalTo(self.view.mas_width);
        make.height.mas_equalTo(PUB_TABBAR_HEIGHT);
    }];
    
    
    MK_WEAK_SELF
    self.commentTextView = [[CXTextView alloc] initWithFrame:CGRectMake(kHalfMargin, kQuarterMargin, SCREEN_WIDTH - kMargin, 30)];
    self.commentTextView.placeholder = WXLocalizedString(@"我来说两句...");
    self.commentTextView.maxLine = 5;
    self.commentTextView.maxLength = 200;
    self.commentTextView.font = kMainFont;
    self.commentTextView.textLengthDidMaxHandlerBlock = ^(UITextView * _Nonnull textView) {
        [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:WXLocalizedString(@"已超出最大字数限制")];
    };
    self.commentTextView.backgroundColor = kWhiteColor;
    self.commentTextView.layer.cornerRadius = 15;
    self.commentTextView.textHeightChangeBlock = ^(CGFloat height) {
        SS(strongSelf)
        strongSelf->commentViewHeight = height;
        
        [weakSelf.commentBottomView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(strongSelf->keyboardHeight + height + kHalfMargin);
        }];
    };
    self.commentTextView.returnHandlerBlock = ^{
        [weakSelf sendCommentNetRequest];
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    };
    [self.commentBottomView addSubview:self.commentTextView];
    
    
    [self.mainTableView addHeaderRefreshWithRefreshingBlock:^{
        if (weakSelf.isTABAnimated) {
            [weakSelf.mainTableView end_Refreshing];
            return;
        }
        weakSelf.currentPageNumber = 1;
        [weakSelf netRequest];
    }];
    
    [self.mainTableView addFooterRefreshWithRefreshingBlock:^{
        if (weakSelf.isTABAnimated) {
            [weakSelf.mainTableView end_Refreshing];
            return;
        }
        weakSelf.currentPageNumber ++;
        [weakSelf netRequest];
    }];
    
    [self setEmptyOnView:self.mainTableView title:WXLocalizedString(@"暂无评论内容") tapBlock:nil];
    
    TABTableAnimated *tabAnimatedView = [TABTableAnimated animatedWithCellClass:TL_CommentsTableViewCell.class cellHeight:110.0];
    tabAnimatedView.animatedCount = 10;
    tabAnimatedView.cellHeight = 110.0;
    tabAnimatedView.canLoadAgain = YES;
    
    tabAnimatedView.adjustBlock = ^(TABComponentManager * _Nonnull manager) {
        manager.animationsWithIndexs(2, 4).remove();
        manager.animations(6, 8).remove();
        
        manager.animation(3).width(105);
        manager.animation(5).topEqualToBottom_offset(3, kHalfMargin).leftEqualTo(0).widthEqualTo(0).line(3);
    };
    self.mainTableView.tabAnimated = tabAnimatedView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSourceArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellName = @"TL_CommentsTableViewCell";
    TL_CommentsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (!cell) {
        cell = [[TL_CommentsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
    }
    cell.commentLabel.numberOfLines = 0;
    cell.commentModel = [self.dataSourceArray wx_objectOrNilAtIndex:indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.hiddenEndLine = indexPath.row == self.dataSourceArray.count - 1;
    
    if (self.chapter_id > 0) {
        if (self.productionType == TL_ProductionTypeComic) {
            [self setNavigationBarTitle:WXLocalizedString(@"评论")];
        } else {
            [self setNavigationBarTitle:[NSString stringWithFormat:WXLocalizedString(@"本章评论（%@）"),[TL_UtilsHelper formatStringWithInteger:self.commentModel.total_count]]];
        }
    } else {
        [self setNavigationBarTitle:[NSString stringWithFormat:WXLocalizedString(@"书评（%@）"),[TL_UtilsHelper formatStringWithInteger:self.commentModel.total_count]]];
    }
    [self setNavigationBarTitle:@"All comments"];
    
    MK_WEAK_SELF;
    cell.productionType = self.productionType;
    cell.replyCommentBlock = ^(TL_CommentsDetailModel *commentModel) {
        [weakSelf showReplyList:commentModel withIndex:indexPath.row];
    };
    cell.gotoCommentDetailsBlock = ^{
        
        TL_CommentReplyListViewController *commentReplyListViewController = [[TL_CommentReplyListViewController alloc] init];
           commentReplyListViewController.commentModel = [self.dataSourceArray wx_objectOrNilAtIndex:indexPath.row];
           commentReplyListViewController.productionType = self.productionType;
           NavigationController *nav = [[NavigationController alloc] initWithRootViewController:commentReplyListViewController];
           [[TL_ViewHelper getCurrentViewController].navigationController presentViewController:nav animated:YES completion:^{
                       
           }];
    };
    cell.deleteCommentBlock = ^(TL_CommentsDetailModel *commentsDetailModel,int type) {
        if (type==0) {
            
            [weakSelf.dataSourceArray removeObject:commentsDetailModel];
            
            weakSelf.commentModel.total_count -= 1;
            
            if (weakSelf.deleteCommentBlock) {
                weakSelf.deleteCommentBlock(commentsDetailModel);
            }
            
        }else{
            
            NSMutableArray *deleteList = [NSMutableArray new];
            
            for (TL_CommentsDetailModel *cdModel in weakSelf.dataSourceArray) {
                if (cdModel.uid == commentsDetailModel.uid) {
                    [deleteList addObject:cdModel];
                }
            }
            
            [weakSelf.dataSourceArray removeObjectsInArray:deleteList];
            
            weakSelf.commentModel.total_count -= deleteList.count;
            
            if (weakSelf.deleteCommentListBlock) {
                weakSelf.deleteCommentListBlock(commentsDetailModel);
            }
            
        }
        
        if (weakSelf.commentModel.total_count == 0) {
            if (weakSelf.chapter_id > 0) {
                if (weakSelf.productionType == TL_ProductionTypeComic) {
                    [weakSelf setNavigationBarTitle:WXLocalizedString(@"评论")];
                } else {
                    [weakSelf setNavigationBarTitle:[NSString stringWithFormat:WXLocalizedString(@"本章评论（%@）"),[TL_UtilsHelper formatStringWithInteger:weakSelf.commentModel.total_count]]];
                }
            } else {
                [weakSelf setNavigationBarTitle:[NSString stringWithFormat:WXLocalizedString(@"书评（%@）"),[TL_UtilsHelper formatStringWithInteger:weakSelf.commentModel.total_count]]];
            }
        }
        
        [self setNavigationBarTitle:@"All comments"];
        [weakSelf.mainTableView reloadData];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TL_CommentsDetailModel *t_model = [self.dataSourceArray wx_objectOrNilAtIndex:indexPath.row];
    [self showReplyList:t_model withIndex:indexPath.row];
}

- (void)showReplyList:(TL_CommentsDetailModel *)model withIndex:(NSInteger)index {
    TL_CommentReplyListViewController *commentReplyListViewController = [[TL_CommentReplyListViewController alloc] init];
    commentReplyListViewController.commentModel = model;
    commentReplyListViewController.productionType = self.productionType;
    NavigationController *nav = [[NavigationController alloc] initWithRootViewController:commentReplyListViewController];
    [self.navigationController presentViewController:nav animated:YES completion:^{
                
    }];
        
    MK_WEAK_SELF;
    commentReplyListViewController.commentsSuccessBlock = ^(TL_CommentsDetailModel * _Nonnull commentModel) {
        model.comment_num++;
        
        NSMutableArray *tmpArray = [NSMutableArray arrayWithArray:model.replay_commons];
        [tmpArray insertObject:commentModel atIndex:0];
        model.replay_commons = [tmpArray copy];
        
        [weakSelf.dataSourceArray replaceObjectAtIndex:index withObject:model];
        
        [weakSelf.mainTableView reloadData];
        
        if (index<3) {
            if (weakSelf.updateCommentDetailBlock) {
                weakSelf.updateCommentDetailBlock(model);
            }
        }
    };
}

//section头间距
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}
//section头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, CGFLOAT_MIN)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

//section底部间距
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}
//section底部视图
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, CGFLOAT_MIN)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.mainTableView) {
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    }
}

- (void)setComment_id:(NSInteger)comment_id
{
    _comment_id = comment_id;
    
    [self resetCommentTextViewPlaceHolder];
}

- (void)resetCommentTextViewPlaceHolder
{
    if (!self.dataSourceArray || self.dataSourceArray.count == 0) {
        return;
    }
    for (TL_CommentsDetailModel *t_model in self.dataSourceArray) {
        if (t_model.comment_id == self.comment_id) {
            self.commentTextView.placeholder = [NSString stringWithFormat:WXLocalizedString(@"回复 ＠%@"), [TL_UtilsHelper formatStringWithObject:t_model.nickname]];
            break;
        }
    }
}


//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)noti
{
    //获取键盘的高度
    keyboardHeight = [[[noti userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    [self.commentBottomView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(keyboardHeight + commentViewHeight + kHalfMargin + kQuarterMargin);
    }];
    [self.commentBottomView.superview layoutIfNeeded];
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)noti
{
    keyboardHeight = PUB_TABBAR_OFFSET;
    [self.commentBottomView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(commentViewHeight + PUB_TABBAR_OFFSET + (PUB_TABBAR_HEIGHT - PUB_TABBAR_OFFSET - 30));
    }];
    [self.commentBottomView.superview layoutIfNeeded];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (![self.commentBottomView pointInside:[self.commentBottomView convertPoint:[[touches anyObject] locationInView:self.view] fromView:self.view] withEvent:event]) {
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    }
}

- (void)netRequest
{
    NSString *url = [APIURLManager commentGoods];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
//    switch (self.productionType) {
//        case TL_ProductionTypeBook:
//            url = commentGoods;
//            parameters = [NSMutableDictionary dictionaryWithDictionary:@{@"book_id":[TL_UtilsHelper formatStringWithInteger:self.production_id]?:@"", @"page_num":[TL_UtilsHelper formatStringWithInteger:self.currentPageNumber]}];
//            break;
//        case TL_ProductionTypeComic:
//            url = Comic_Comment_List;
//            parameters = [NSMutableDictionary dictionaryWithDictionary:@{@"comic_id":[TL_UtilsHelper formatStringWithInteger:self.production_id]?:@"", @"page_num":[TL_UtilsHelper formatStringWithInteger:self.currentPageNumber]}];
//            break;
//        default:
//            break;
//    }
    
    if (self.chapter_id > 0) {
        [parameters setObject:[TL_UtilsHelper formatStringWithInteger:self.chapter_id]?:@"" forKey:@"chapter_id"];
    }
    
    [self.mainTableView tab_startAnimation];
    self.isTABAnimated = YES;
    
    MK_WEAK_SELF
    
    [APIManager sendGetRequest:url parameters:@{@"worksId":[TL_UtilsHelper formatStringWithInteger:self.production_id],@"pageNum":[TL_UtilsHelper formatStringWithInteger:self.currentPageNumber],@"pageSize":@"10"} model:TL_CommentsDetailModel.class success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        [weakSelf.mainTableView tab_endAnimationEaseOut];
        weakSelf.isTABAnimated = NO;
        
        weakSelf.commentBottomView.hidden = NO;
        
        if (success) {
            weakSelf.mainTableView.tabAnimated = nil;
            NSArray *commentList = [TL_CommentsDetailModel mj_objectArrayWithKeyValuesArray:requestModel.data[@"records"]];
            int currntPage = [requestModel.data[@"current"] intValue];
            int totalPage = [requestModel.data[@"pages"] intValue];
            
            if (weakSelf.currentPageNumber == 1) {
                [weakSelf.mainTableView showRefreshFooter];
                [weakSelf.dataSourceArray removeAllObjects];
                weakSelf.dataSourceArray = [NSMutableArray arrayWithArray:commentList];
            } else {
                [weakSelf.dataSourceArray addObjectsFromArray:commentList];
            }
            if (totalPage <= currntPage) {
                [weakSelf.mainTableView hideRefreshFooterAndHiddenLab];
            }
            
            [weakSelf resetCommentTextViewPlaceHolder];
            TL_CommentsModel * tt_model = [TL_CommentsModel new];
            tt_model.list = commentList;
            weakSelf.commentModel = tt_model;
            
        } else {
            [weakSelf.mainTableView hideRefreshFooter];
        }
        [weakSelf.mainTableView endRefreshing];
        [weakSelf.mainTableView reloadData];
        [weakSelf.mainTableView ly_endLoading];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [weakSelf.mainTableView tab_endAnimationEaseOut];
        weakSelf.isTABAnimated = NO;
        
        weakSelf.commentBottomView.hidden = NO;
        
        [weakSelf.mainTableView endRefreshing];
        [weakSelf.mainTableView ly_endLoading];
        [weakSelf.mainTableView hideRefreshFooter];
        [TL_TopAlertManager showAlertWithError:error defaultText:nil];
    }];
}

- (void)sendCommentNetRequest
{
    if ([self.commentTextView.text isEqualToString:@""]) {
        return;
    }
    
    NSString *t_text = self.commentTextView.text;
    self.commentTextView.text = @"";
    
    NSString *url = [APIURLManager commentGoods];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    [parameters setObject:[TL_UtilsHelper formatStringWithInteger:self.production_id] forKey:@"worksId"];
    [parameters setObject:t_text forKey:@"content"];
    
    MK_WEAK_SELF
    
    [APIManager sendPostRequest:url parameters:parameters model:TL_CommentsDetailModel.class success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
            weakSelf.comment_id = 0;
            
            weakSelf.commentTextView.placeholder = WXLocalizedString(@"我来说两句...");
            
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"评论成功")];
            
            self.currentPageNumber = 1;
            [self.dataSourceArray removeAllObjects];
            [self.mainTableView reloadData];
            [self netRequest];
            
            [weakSelf.mainTableView reloadData];
            [weakSelf.mainTableView ly_endLoading];
            
        } else {
            weakSelf.commentTextView.text = t_text;
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.msg];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [TL_TopAlertManager showAlertWithError:error defaultText:WXLocalizedString(@"评论失败")];
    }];
}

- (void)popViewController
{
    [super popViewController];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
